package com.thinkgem.jeesite.common.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;

import com.thinkgem.jeesite.common.filter.utils.XssHttpServletRequestWraper;

public class CookieHttpOnlyFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request; 
        HttpServletResponse resp = (HttpServletResponse) response;
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
            for(Cookie cookie : cookies){
             //tomcat7 支持该属性，tomcat6 不支持
             String value = cookie.getValue(); 
                      StringBuilder builder = new StringBuilder(); 
                      builder.append("JSESSIONID=" + value + "; "); 
                      builder.append("Secure; "); 
                      builder.append("HttpOnly; "); 
                      Calendar cal = Calendar.getInstance(); 
                      cal.add(Calendar.HOUR, 1); 
                      Date date = cal.getTime(); 
                      Locale locale = Locale.CHINA; 
                      SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",locale); 
                      builder.append("Expires=" + sdf.format(date)); 
                      resp.setHeader("Set-Cookie", builder.toString());
            }
           
            chain.doFilter(request, response);
        }else{
            StringBuilder builder = new StringBuilder(); 
            String id = (String) SecurityUtils.getSubject().getSession().getId(); 
            builder.append("JSESSIONID=" + id + "; "); 
            builder.append("Secure; "); 
            builder.append("HttpOnly; "); 
            Calendar cal = Calendar.getInstance(); 
            cal.add(Calendar.HOUR, 1); 
            Date date = cal.getTime(); 
            Locale locale = Locale.CHINA; 
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss",locale); 
            builder.append("Expires=" + sdf.format(date)); 
            resp.setHeader("Set-Cookie", builder.toString());
            chain.doFilter(request, response);
        }
        
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        
    }

}
